﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using EntityBinder.Interface;

namespace EntityBinder.Internal
{
	/// <summary>
	/// This class provide access for field in class.
	/// </summary>
	internal class Field : IMemberAccess
	{
		/// <summary>
		/// Field name.
		/// </summary>
		private string m_fieldName;

		/// <summary>
		/// Type of the container.
		/// </summary>
		private Type m_type;

		/// <summary>
		/// FieldInfo relative to the field.
		/// </summary>
		private System.Reflection.FieldInfo m_fieldInfo;

		public string Name
		{
			get { return m_fieldName; }
		}

		public Type Type
		{
			get { return m_type; }
		}

		/// <summary>
		/// Create a field object by specifying the name of the field which it will apply and the type of the container.
		/// </summary>
		/// <param name="_name">Name of the field.</param>
		/// <param name="_type">Type of the container of the field.</param>
		public Field(string _name, Type _type)
		{
			m_fieldName = _name;
			m_type = _type;

			m_fieldInfo = m_type.GetField(m_fieldName, MemberAccessFactory.SEARCH_FLAGS);

			if(m_fieldInfo == null)
			{
				throw new EntityBinderException("Field", "<ctor>", "The field " + _name + " does not exists in the type " + _type);
			}
		}

		public virtual object Get(object _data)
		{
			return m_fieldInfo.GetValue(_data);
		}

		public virtual void Set(object _data, object _newValue)
		{
			m_fieldInfo.SetValue(_data, _newValue);
		}
	}
}
